package com.hudongwx.shansun.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hudongwx.shansun.R;
import com.hudongwx.shansun.define.MyPopuWinDown;
import com.hudongwx.shansun.utlis.API;
import com.hudongwx.shansun.utlis.MyJSONobject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

@ContentView(R.layout.activity_display)
public class DisplayActivity extends AppCompatActivity {
    private String TAG = "DisplayActivity";
    @ViewInject(R.id.display_recy)
    private RecyclerView recyclerView;
    @ViewInject(R.id.display_tv)
    private TextView tv;
    @ViewInject(R.id.display_iv_1)
    private ImageView iv1;
    @ViewInject(R.id.display_iv_2)
    private ImageView iv2;
    @ViewInject(R.id.display_ll_1)
    private LinearLayout ll_1;
    @ViewInject(R.id.display_ll_4)
    private LinearLayout ll_4;
    @ViewInject(R.id.display_ll_5)
    private LinearLayout ll_5;
    private String link, specialId;
    private DisRecyAdapter disRecyAdapter;
    private List<Item> list1;
    private int nowpage = 1;
    @ViewInject(R.id.display_ll_6)
    private LinearLayout ll_6;

    private MyPopuWinDown myPopuWinDown;
    private Map<Object, String> map;
    private List<Integer> intList;
    private View.OnClickListener onClickListener;
    private int[] imgs = new int[5];
    private List<Integer> list;
    private LinearLayout layout;
    private TextView tvLL;
    private GridView grid;
    private String url, title;
    private String shareTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
     /*   link = getIntent().getStringExtra("link");
        title = getIntent().getStringExtra("title");
        String viewType = getIntent().getStringExtra("viewType");*/

       /* if (viewType.equals("3")) {
            initRecy("0");
        } else if (viewType.equals("7")) {
            iniyRecy2();
            ll_6.setVisibility(View.GONE);
        }*/

        String data = getIntent().getStringExtra("url");
        String[] attrs = data.split("\\|");
        shareTitle=attrs[1];
        //设置标题
        link = attrs[0];
        String viewType=attrs[2];

        Log.i(TAG, "onCreate: "+link);
        if (viewType.equals("3")) {
            initRecy("0");
            tv.setText(attrs[1]);
        } else if (viewType.equals("7")) {
            iniyRecy2();
            ll_6.setVisibility(View.GONE);
            tv.setText(attrs[1]);
        }


    }

    //分享的点击
    @Event(R.id.share_iv)
    private void Share(View view) {

        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("ShareSDK");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);

    }

    //点击时有货
    @Event(R.id.display_ll_1)
    private void ll_1Btn(View view) {
        if (iv2.isSelected()) {
            iv2.setSelected(false);
            analysis("0");
            initRecy("0");
        } else {
            iv2.setSelected(true);
            analysis("1");
            initRecy("1");
        }
    }
    //加载筛选的网址

    //筛选的点击时间
    @Event(R.id.display_ll_2)
    private void ll_2Btn(final View view) {
        myPopuWinDown = new MyPopuWinDown(this, new MyPopuWinDown.ItemOnClick() {
            @Override
            public void tv2(final TextView tv2) {

                RequestParams params = new RequestParams(API.fragment_screen(link));
                x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
                    @Override
                    public void onSuccess(MyJSONobject result) {
                        try {
                            JSONArray arry = result.getJSONArray("data");
                            if (arry.length() == 2) {
                                JSONObject jsonObject = arry.getJSONObject(0);
                                String name = jsonObject.getString("name");
                                tv2.setText(name);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });


            }

            @Override
            public void tv3(final TextView tv3) {
                RequestParams params = new RequestParams(API.fragment_screen(link));
                x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
                    @Override
                    public void onSuccess(MyJSONobject result) {
                        try {
                            JSONArray arry = result.getJSONArray("data");
                            Log.i(TAG, "onSuccess: " + arry.length());
                            if (arry.length() == 1) {
                                JSONObject jsonObject = arry.getJSONObject(0);
                                String name = jsonObject.getString("name");
                                tv3.setText(name);
                            } else {
                                JSONObject jsonObject = arry.getJSONObject(1);
                                String name = jsonObject.getString("name");
                                tv3.setText(name);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }

            @Override
            public void line(final LinearLayout linearLayout) {
                layout = linearLayout;
                RequestParams params = new RequestParams(API.fragment_screen(link));
                x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
                    @Override
                    public void onSuccess(MyJSONobject result) {
                        try {
                            JSONArray arry = result.getJSONArray("data");
                            if (arry.length() == 2) {
                                JSONObject jsonObject = arry.getJSONObject(0);
                                JSONArray attr = jsonObject.getJSONArray("attr");

                                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                                onClickListener = new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        tvLL = (TextView) v;
                                        if ("不限".equals(tvLL.getText())) {
                                            int count = linearLayout.getChildCount();
                                            for (int i = 0; i < count; i++) {
                                                linearLayout.getChildAt(i).setSelected(false);
                                            }
                                            v.setSelected(true);
                                        } else {
                                            linearLayout.getChildAt(0).setSelected(false);
                                            v.setSelected(!v.isSelected());
                                        }


                                    }
                                };
                                list = new ArrayList<Integer>();
                                for (int i = 0; i < attr.length(); i++) {
                                    TextView Sex = new TextView(DisplayActivity.this);
                                    JSONObject jsonObject1 = attr.getJSONObject(i);
                                    Sex.setPadding(120, 10, 20, 10);
                                    list.add(i);
                                    Sex.setBackgroundResource(R.drawable.mypopu_shape);
                                    Sex.setGravity(Gravity.CENTER);
                                    Sex.setOnClickListener(onClickListener);
                                    linearLayout.setLayoutParams(layoutParams);
                                    Sex.setText(jsonObject1.getString("typeName"));
                                    linearLayout.addView(Sex);
                                    if (i == 0) {
                                        Sex.setSelected(true);
                                    }
                                }
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }

            @Override
            public void gird(final GridView gridView) {
                grid = gridView;
                RequestParams params = new RequestParams(API.fragment_screen(link));
                x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
                    @Override
                    public void onSuccess(MyJSONobject result) {
                        try {
                            JSONArray arry = result.getJSONArray("data");
                            if (arry.length() == 1) {
                                JSONObject jsonObject = arry.getJSONObject(0);
                                JSONArray attr = jsonObject.getJSONArray("attr");
                                gridView.setAdapter(new MyAdapter(attr));
                            } else {
                                JSONObject jsonObject = arry.getJSONObject(1);
                                JSONArray attr = jsonObject.getJSONArray("attr");
                                gridView.setAdapter(new MyAdapter(attr));
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });


            }

            //重置的按钮
            @Override
            public void btn1(Button button) {
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        int count = layout.getChildCount();
                        if (count != 0) {
                            layout.getChildAt(0).setSelected(true);
                            for (int i = 1; i < count; i++) {
                                layout.getChildAt(i).setSelected(false);
                            }
                        }

                        int childCount = grid.getChildCount();
                        Button btn = (Button) grid.getChildAt(0);
                        btn.setBackgroundResource(R.color.hometitle);
                        //  btn.setSelected(true);
                        for (int i = 1; i < childCount; i++) {
                            View childAt = grid.getChildAt(i);
                            //childAt.setBackgroundResource(android.R.color.white);
                            childAt.setSelected(false);
                        }

                    }
                });
            }

            //提交的按钮
            @Override
            public void btn2(Button button) {
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (intList.size() != 0) {
                            for (int i = 0; i < intList.size(); i++) {
                                Toast.makeText(DisplayActivity.this, map.get(intList.get(i)), Toast.LENGTH_SHORT).show();
                                map.remove(i);
                                intList.remove(i);
                            }

                            myPopuWinDown.dismiss();
                        } else {
                            Toast.makeText(DisplayActivity.this, "请填入信息", Toast.LENGTH_SHORT).show();
                        }

                    }
                });
            }
        });
        myPopuWinDown.showAtLocation(view, Gravity.FILL, 0, 0);

    }

    class MyAdapter extends BaseAdapter {
        private JSONArray arry;
        Map<Integer, Button> mapBut = new HashMap<>();

        public MyAdapter(JSONArray arry) {
            this.arry = arry;
        }

        @Override
        public int getCount() {
            return arry.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return arry.getJSONObject(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            Button but = mapBut.get(position);


            if (but == null) {
                but = new Button(DisplayActivity.this);
                mapBut.put(position, but);
                but.setTextSize(15);
                but.setBackgroundResource(R.drawable.mypopu_shape);


                but.setSelected(true);


                JSONObject jsonObject = null;
                try {
                    jsonObject = arry.getJSONObject(position);
                    final String typeName = jsonObject.getString("typeName");
                    but.setText(typeName);
                    map = new HashMap<>();
                    intList = new ArrayList<>();
                    if (position == 0) {
                        but.setBackgroundResource(R.color.hometitle);
                        map.put(position, typeName);
                        intList.add(position);
                    }
                    but.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int childCount = grid.getChildCount();
                            Button bnt = (Button) v;
                            if ("不限".equals(bnt.getText())) {
                                for (int i = 0; i < childCount; i++) {
                                    Button btn = (Button) grid.getChildAt(i);
                                    btn.setSelected(false);
                                    map.remove(i);
                                }
                                v.setBackgroundResource(R.color.hometitle);
                                map.put(position, typeName);
                                intList.add(position);
                            } else {
                                Button btn = (Button) grid.getChildAt(0);
                                btn.setBackgroundResource(android.R.color.white);
                                if (v.isSelected()) {
                                    v.setSelected(false);
                                    map.remove(position);
                                } else {
                                    v.setSelected(true);
                                    map.put(position, typeName);
                                    intList.add(position);
                                }
                            }
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }


            return but;


        }
    }

    //加载adapter 的布局
    private void iniyRecy2() {
        RequestParams params = new RequestParams(API.fragment_2_item("gender:female"));
        x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
            @Override
            public void onSuccess(MyJSONobject result) {
                tv.setText(title);
                try {
                    JSONArray data = result.getJSONArray("data");
                    Log.i(TAG, "onSuccess: "+data.length());
                    RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(DisplayActivity.this);
                    recyclerView.setLayoutManager(layoutManager);
                    recyclerView.setAdapter(new DisRecyAdapter2(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    class DisRecyAdapter2 extends RecyclerView.Adapter {
        private JSONArray arry;
        public DisRecyAdapter2(JSONArray arry) {
            this.arry = arry;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.display2_item, parent, false);
            return new MyViewHoler2(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            MyViewHoler2 myViewHoler2= (MyViewHoler2) holder;
            try {
                JSONObject jsonObject = arry.getJSONObject(position);
                String imgUrl = jsonObject.getString("imgUrl");
                 x.image().bind(myViewHoler2.iv,imgUrl);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public int getItemCount() {

            return arry.length();
        }
    }

    class MyViewHoler2 extends RecyclerView.ViewHolder {
        ImageView iv;

        public MyViewHoler2(View itemView) {
            super(itemView);
            iv = (ImageView) itemView.findViewById(R.id.display2_item_iv);
        }
    }


    private void initRecy(final String show_stock) {
        disRecyAdapter = new DisRecyAdapter();
        analysis(show_stock);
        recyclerView.setAdapter(disRecyAdapter);
        final GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE && gridLayoutManager.findLastVisibleItemPosition() + 1 == disRecyAdapter.getItemCount()) {
                    analysis(show_stock);
                }

                super.onScrollStateChanged(recyclerView, newState);

            }
        });
    }

    //构造适配器
    class DisRecyAdapter extends RecyclerView.Adapter {
        private List<Item> data = new ArrayList<>();

        public DisRecyAdapter() {
        }

        public DisRecyAdapter(List<Item> data) {
            this.data = data;
        }

        //清空数据
        public void clear() {
            data.clear();
            notifyDataSetChanged();
        }

        //加载下一页的数据
        public void addMore(List<Item> tempData) {
            data.addAll(tempData);
            notifyItemRangeChanged(data.size() - tempData.size(), tempData.size());
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.display_item, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

            MyViewHolder myViewHolder = (MyViewHolder) holder;
            final Item item = data.get(position);
            x.image().bind(myViewHolder.iv2, item.getImg640url());
            myViewHolder.tv1.setText(item.getCrazyPrice());
            myViewHolder.tv2.setText(item.getShopPrice());
            myViewHolder.tv3.setText(item.getDiscount());
            myViewHolder.tv4.setText(item.getFlashPrice());
            myViewHolder.tv5.setText(item.getName());

        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView iv2;
        TextView tv1, tv2, tv3, tv4, tv5;
        View itenm;

        public MyViewHolder(View itemView) {
            super(itemView);
            iv2 = (ImageView) itemView.findViewById(R.id.display_item_iv_1);
            tv1 = (TextView) itemView.findViewById(R.id.display_item_tv_1);
            tv2 = (TextView) itemView.findViewById(R.id.display_item_tv_2);
            tv3 = (TextView) itemView.findViewById(R.id.display_item_tv_3);
            tv4 = (TextView) itemView.findViewById(R.id.display_item_tv_4);
            tv5 = (TextView) itemView.findViewById(R.id.display_item_tv_5);
            this.itenm = itemView;
        }
    }

    //解析数据
    private void analysis(String show_stock) {

        RequestParams params = new RequestParams(API.fragment_1_item(link, nowpage + "", show_stock));
        x.http().get(params, new Callback.CommonCallback<MyJSONobject>() {
            @Override
            public void onSuccess(MyJSONobject result) {
                JSONArray data = null;
                List<Item> items = Parseitem(result);
                disRecyAdapter.addMore(items);

                try {
                    String topImg = result.getString("topImg");
                    specialId = result.getString("specialId");
                    x.image().bind(iv1, topImg);
                    String title = result.getString("title");
                    tv.setText(title);
                    data = result.getJSONArray("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                nowpage++;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public List<Item> Parseitem(JSONObject data) {
        List<Item> list = new ArrayList<>();
        try {
            JSONArray data1 = data.getJSONArray("data");
            for (int i = 0; i < data1.length(); i++) {
                list.add(new Item(data1.getJSONObject(i)));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    class Item {
        String img640url;
        String crazyPrice;
        String shopPrice;
        String discount;
        String flashPrice;
        String name;
        String goodsId;

        public String getImg640url() {
            return img640url;
        }

        public void setImg640url(String img640url) {
            this.img640url = img640url;
        }

        public String getCrazyPrice() {
            return crazyPrice;
        }

        public void setCrazyPrice(String crazyPrice) {
            this.crazyPrice = crazyPrice;
        }

        public String getShopPrice() {
            return shopPrice;
        }

        public void setShopPrice(String shopPrice) {
            this.shopPrice = shopPrice;
        }

        public String getDiscount() {
            return discount;
        }

        public void setDiscount(String discount) {
            this.discount = discount;
        }

        public String getFlashPrice() {
            return flashPrice;
        }

        public void setFlashPrice(String flashPrice) {
            this.flashPrice = flashPrice;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getGoodsId() {
            return goodsId;
        }

        public void setGoodsId(String goodsId) {
            this.goodsId = goodsId;
        }

        public Item(JSONObject jsonObject) throws JSONException {
            img640url = jsonObject.getString("img640url");
            crazyPrice = jsonObject.getString("crazyPrice");
            shopPrice = jsonObject.getString("shopPrice");
            discount = jsonObject.getString("discount");
            flashPrice = jsonObject.getString("flashPrice");
            name = jsonObject.getString("name");

            goodsId = jsonObject.getString("goodsId");
        }

    }
}
